package ui.controls;


import java.awt.Color;

import ui.controls.LED;
import ui.control.switches.*;
import ui.Assets;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

import cpu.components.DeviceUnit;
import ui.control.binary.Event;
import ui.control.binary.States;
import ui.Console;

public class SwitchBank extends JPanel implements ui.control.binary.Event, cpu.interfaces.Device {
	protected Switch[] bank;
	
	protected int width = 0;
	protected int height = 0;
	protected String name;
	private Console owner;
	
	private cpu.components.DeviceUnit controller;
	
	boolean changed = false;
	
	public SwitchBank( Assets assets, Console owner, String name, int switches, SwitchColors color, SwitchSizes size  ) {
		setLayout( null );
		this.owner = owner;

		this.name = name;
		int start = 48;
		JLabel label = new JLabel( name );
		label.setLocation( 0, 2 );
		label.setSize( start, 48 );
		label.setHorizontalAlignment( SwingConstants.RIGHT);
		this.add( label );
		
		start += 4;
		bank = new Switch[switches];
		int width;
		
		this.width = start;
		for( int i = 0; i < bank.length; i++ ) {
			bank[i] = new Switch( assets, this, i, color, size );
			width = bank[i].getWidth( );
			bank[i].setLocation( start + width * i, 0 );
			this.add( bank[i] );
			
			label = new JLabel( Integer.toString( i ) );
			label.setLocation( start + width * i, width + 6 );
			label.setSize( width, 10 );
			label.setHorizontalAlignment(SwingConstants.CENTER);
			this.add( label );
			
			this.width += width;
		}
		this.height = bank[0].getHeight( ) + 32;
		//setSize( bank[0].getWidth( ) * bank.length, height );
		setSize( this.width, this.height );
		
	}
	public int getWidth( ) {
		return width;
	}
	public int getHeight( ) {
		return height;
	}
	public void toggle( int i ) {
		bank[i].toggle( );
	}
	public void toggleOn( int i ) {
		bank[i].toggleOn( );
	}
	public void toggleOff( int i ) {
		bank[i].toggleOff( );
	}
	public void changed( int id, ui.control.binary.States state ) {
		owner.changed( this, id, state );
	}
	
	public void enroll( int id, DeviceUnit controller ) {
		this.controller = controller;
		controller.enroll( id, this );
	}
	
	public void get( ) {
		for( int i = 0; i < bank.length; i++ ) {
			ui.control.binary.States state = bank[i].getState( );
			if( state == States.ON )
				controller.DBR.bit( i ).value = true;
			else
				controller.DBR.bit( i ).value = false;
		}
		changed = false;
	}
	
	// switchbanks do not support output
	public void put( ) {
		
	}
	
	public void status( ) {
		if( changed ) {
			controller.DSR.fromJavaInt( 1 );
		} else {
			controller.DSR.fromJavaInt( 0 );
		}
	}
	
}
